package com.example.test2.activity;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;

import com.example.test2.MainActivity;
import com.example.test2.R;
import com.example.test2.databinding.ActivityLoginBinding;
import com.example.test2.db.control.UserDbController;
import com.example.test2.db.entity.User;
import com.example.test2.http.Constants;
import com.example.test2.utils.ToastUtils;


// TODO: 2024/5/25 登陆
public class LoginActivity extends BaseActivity<ActivityLoginBinding> implements View.OnClickListener {

    private User user;

    @Override
    protected void initData() {
        super.initData();
        UserDbController dbUserController = UserDbController.getInstance(this);
        user = dbUserController.searchByName(Constants.PHONE);
        getBinding().titleBar.setTitle("欢迎登录" + getString(R.string.app_name));
    }

    @Override
    protected void initClick() {
        super.initClick();
        getBinding().btLogin.setOnClickListener(this);
        getBinding().titleBar.setLeftIconOnClickListener(view -> {exit();});
        getBinding().btLogin.setOnClickListener(this);
    }

    private void exit() {
        finish();
        new Handler().postDelayed(() -> {
            System.exit(0);
        }, 500);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected ActivityLoginBinding onCreateViewBinding(@NonNull LayoutInflater layoutInflater) {
        return ActivityLoginBinding.inflate(layoutInflater);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                login();
                break;
        }
    }

    private void login() {
        String pwd = getBinding().etPwd.getText().toString();
        if (TextUtils.isEmpty(pwd)) {
            ToastUtils.getInstance().show(this, "密码不能为空！");
            return;
        }
        if (user.getPwd().equals(pwd)) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        } else {
            ToastUtils.getInstance().show(this, "密码错误！");
        }
    }
}